package com.example.healthmonitoringbe;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;

import java.sql.SQLException;
import java.util.Collections;
import java.util.Scanner;

public class MyGenerator {
    /**
     * 数据源配置
     */
    private static final DataSourceConfig.Builder DATA_SOURCE_CONFIG = new DataSourceConfig
            .Builder("jdbc:mysql://localhost:3306/health_monitoring_db" +
            "?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai",
            "root", "ysr_xian");

    /**
     * 执行 run
     */
    public static void main(String[] args) throws SQLException {
        String projectPath = System.getProperty("user.dir");
        String tableName = scanner();
        FastAutoGenerator.create(DATA_SOURCE_CONFIG)
                // 全局配置
                .globalConfig(builder -> {
                    builder.author("ysr_xian") // 设置作者
                            .fileOverride() // 覆盖已生成文件
                            .outputDir(projectPath + "/src/main/java"); // 指定输出目录
                })
                // 包配置
                .packageConfig((scanner, builder) -> {
                    builder.parent("com.example")
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, projectPath + "/src/main/resources/mapper"));
                })
                // 策略配置
                .strategyConfig(builder ->
                        builder.addInclude(tableName)
                                .entityBuilder()
                                .enableLombok()
                                .enableTableFieldAnnotation()     // 开启生成实体时生成字段注解
                                .controllerBuilder()
                                .enableRestStyle()                // 开启生成@RestController 控制器
                                .mapperBuilder()
                                .enableMapperAnnotation()
                )
                .execute();
    }

    /**
     * 读取控制台内容信息
     */
    private static String scanner() {
        Scanner scanner = new Scanner(System.in);
        System.out.println(("请输入表名" + "："));
        if (scanner.hasNext()) {
            String next = scanner.next();
            if (StringUtils.isNotBlank(next)) {
                return next;
            }
        }
        throw new MybatisPlusException("请输入正确的表名" + "！");
    }
}
